﻿namespace DeltaGroup.WheelOfJeopardy.UI.Validations
{
    using System;
    using System.Collections.Generic;
    using System.Globalization;
    using System.Windows.Controls;

    public class DataTypeValidationRule : ValidationRule
    {
        #region Fields

        private static Dictionary<SupportedTypes, Func<object, object>> _converters;

        #endregion Fields

        #region Constructors

        /// <summary>
        /// Initializes the <see cref="DataTypeValidationRule"/> class.
        /// </summary>
        static DataTypeValidationRule()
        {
            _converters = new Dictionary<SupportedTypes, Func<object, object>>
                              {
                                  {SupportedTypes.Integer, (o) => Convert.ToInt32(o)},
                                  {SupportedTypes.DateTime, (o) => Convert.ToDateTime(o)},
                                  {SupportedTypes.Decimal, (o) => Convert.ToDecimal(o)}
                              };
        }

        #endregion Constructors

        #region Enumerations

        public enum SupportedTypes
        {
            Integer,
            DateTime,
            Decimal
        }

        #endregion Enumerations

        #region Properties

        /// <summary>
        /// Gets or sets the type.
        /// </summary>
        /// <value>The type.</value>
        public SupportedTypes Type
        {
            get; set;
        }

        #endregion Properties

        #region Methods

        /// <summary>
        /// When overridden in a derived class, performs validation checks on a value.
        /// </summary>
        /// <param name="value">The value from the binding target to check.</param>
        /// <param name="cultureInfo">The culture to use in this rule.</param>
        /// <returns>
        /// A <see cref="T:System.Windows.Controls.ValidationResult"/> object.
        /// </returns>
        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            var converter = _converters[Type];

            try
            {
                var val = converter(value);
                return new ValidationResult(true, null);
            }
            catch (Exception ex)
            {
                return new ValidationResult(false, string.Format("This should be a {0}", Type.ToString()));
            }
        }

        #endregion Methods
    }
}